import message from 'ant-design-vue/es/message'
import axios from 'axios'
import { H } from "./addhttpreq";
import validate from "./pramirymodel"
import store from "../src/store/index.js"
import CryptoJS from 'crypto-js'
import ColumnGroup from 'ant-design-vue/es/vc-table/sugar/ColumnGroup';


let datestr={d:"实习日志",w:"实习周志",m:"实习月志"}
let msg={};
let captcha=false;
// axios主体
var request=axios.create({
    baseURL:"/swagger",
    timeout:12000
    
})

// 请求拦截器
request.interceptors.request.use(config =>{
        if (config.headers.v=="1.6.36") { 
            config.baseURL="/app";
        }else{
            config.baseURL="/swagger";
        }
        let a=H(config.data,config.url)
            config.headers.n="content,practicePurpose,practiceContent,practiceRequirement,otherRequirement,practiceDescript,securityBook,responsibilities,selfAppraisal,file,startDate,addFilejson",
            config.headers.m = a.md5,
            config.headers.t = a.tstr,
            config.headers.s = a.iArrStr;
    return config
    
    },
    (error)=>{
        message.error('This is an error message');
        return Promise.reject(error)
    }
)

// 登入
export function relogin(user,password,isc){
    const ldata={
        loginType: "NORMAL",
        username: user,
        password: CryptoJS.MD5(password).toString(),
        userType: "PERSON"
       }
    if(isc!=''){
        ldata.captcha=isc
    }
    return request({
       url:"/login/login.action" ,
       data:ldata,
       headers:{
        "Content-Type":"application/x-www-form-urlencoded"
       },
       method:"post",
       
    })
}
// 登入设置cookie
export function getperson(){
    
    return request({
        method:"get",
        url:"/personal/",
        
        headers:{
                "Cache-Control": "max-age=0",
                "Accept":`text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7`,
               
        }

        
    })
}
// 网页登入自动获取cookie
export function getcookie(){
    return request({
        url:"/login/personalLoginerInfo.action",
        method:"post",
        headers:{
            "Content-Type":"application/x-www-form-urlencoded",
        }
    })
    
}

// 个人信息获取
export async function getpersoninfo(type='m') {
    let res;
    await request({
            url:'/common/plugin/term/loadTerms.action',
            method:"post",
            data:{
                type:28
            },
            headers:{
                "Content-Type":"application/x-www-form-urlencoded"
            }
        }).then(val=>{
            res=val?.data || {}
            const{datas,schoolTermId}={...res.data}
            msg={datas,schoolTermId,...msg}

    })
  
    return  request({
                url:'/practice/student/blogs/loadTaskList.action',
                method:"post",
                data:{
                    schoolTermId:res.data.schoolTermId,
                    type:type
                },
                headers:{
                    "Content-Type":"application/x-www-form-urlencoded"
                }
            })
    
}
// 签到签退

export async function qiandao(traineeId=80766666){
    // let temploc={};
    //     await request({
    //         url:"/common/getOpenId.action",
    //         method:"post",
    //         headers:{
    //             'Content-Type': 'application/x-www-form-urlencoded',
    //             'v':'1.6.36'
    //         },
    //         data:{

    //         }
    //     }).then(val=>{
    //         console.log(val,"lao");
    //     })
        // /login/login!checkWxBind.action
    // await request({

    //     url:"/student/progress/ProjectList.action",
    //     method:"post",
    //     headers:{
    //         'Content-Type': 'application/x-www-form-urlencoded',
    //         'v':'1.6.36'
    //     },
    //     data:{
    //     }
    // }).then(vv=>{
    //     temploc=vv?.data.data[0].projectList[0].datas[0]
    // })
    // await request({
    //     url:"/student/practiceplan/independent/LoadSummaryPostById.action",
    //     method:"post",
    //     headers:{
    //         'Content-Type': 'application/x-www-form-urlencoded',
    //         'v':'1.6.36'
    //     },
    //     data:{
    //         summaryPostId:temploc?.summaryPostId
    //     }
    // }).then(svv=>{
    //     temploc={...temploc,...svv.data.data}
    // })
    // console.log(temploc,"我是签到");
    // return request({
    //     url:"/student/clock/Post.action",
    //     method:'post',
    //     headers:{
    //         'Content-Type': 'application/x-www-form-urlencoded',
    //         'v':'1.6.36'
    //     },
    //     data:{
    //         traineeId,
    //         adcode,
    //         address,
    //         deviceName:"iphone16",
    //         punchInStatus,
    //         clockStatus
    //     }
    // })
}  
let tempmessage='';
// 大模型回答
export async function bigmodel(userinfo,personalinfo){
    let tempurl;
    
    let temppsepciality =userinfo.speciality ||personalinfo[0]?.plan.slice(3,7)
    var params = {
        "header": {
            "app_id": "a1ef9519",
            "uid": userinfo.user
        },
        "parameter": {
            "chat": {
                "domain": "generalv2",
                "temperature": 0.5,
                "max_tokens": 1024
            }
        },
        "payload": {
            "message": {
                "text": [
                    {
                        "role": "user",
                        "content": `给我生成一篇${userinfo.date}的${temppsepciality}${datestr[userinfo.log]}`
                    }
                ]
            }
        }
    }
    await validate().then(url=>{tempurl=url})
        let wws=new WebSocket(tempurl)
        var temptext="";
        wws.onmessage=(result)=>{
            const res=JSON.parse(result.data)
            temptext+=res?.payload?.choices?.text[0]?.content  
        }
        wws.onopen=e=>{
            wws.send(JSON.stringify(params))
        }
        await new Promise((reso,reje)=>{
            wws.onclose=e=>{
                
                let temphh=temptext.split('\n\n'); 
                temphh.shift()
                temphh=temphh.map(item=>{
                    return `<p style="box-sizing:border-box;margin-top:0px;margin-bottom:0px;padding:0px;white-space:pre-wrap;background-color:rgba(255, 255, 255, 0.86);color:#07133E;line-height:26px;word-break:break-word;font-family:-apple-system, BlinkMacSystemFont, &quot;font-size:16px;letter-spacing:0.5px;">
                    <span style="box-sizing:border-box;display:inline-block;margin-top:1em;">${item}</span></p>`
                })
                temphh=temphh.join('')
                console.log(`正在提交${userinfo.date+''+datestr[userinfo.log]}`,"\n",temphh);
                userinfo.content=temphh
                daybook(userinfo,personalinfo).then(val=>{
                    tempmessage=val?.data.msg
                })
                // allsubmit(userinfo,personalinfo)
                reso('success')
            }
            wws.onerror = e => {
                clearTimeout(this.playTimeout)
                this.setStatus('error')
                alert('WebSocket报错，请f12查看详情')
                console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`)
                reje("fail")
            }
        })
        
    return tempmessage
    
}
// 日，月，周，志
export function daybook(userinfo,personalinfo) {
    let gdata={
        traineeId:personalinfo.traineeId,
        title: datestr[userinfo.log],
        content:userinfo.content,
        status: 1,
        visicty: 2,
        type: userinfo.log,//w,m,d周志日志
        startDate: userinfo.date,
        addFilejson: [],
    };
    if (userinfo.endDate!=''&&userinfo.endDate!=null&&userinfo.endDate!='d') {
        gdata.endDate=userinfo.endDate
    }
  

    return request({
        url:"/practice/student/blogs/save.action",
        method:"post",
        headers:{
            "Content-Type":"application/x-www-form-urlencoded"
        },
        data:gdata
    })
}


       





        
         
    
   


// 初始化浏览器信息
async function initmsg(){
    await getperson().then((a) => {})
   
}
// 设置个人信息
export async function writemsg(user,password,isc){
    if (isc=='') {
        await initmsg()
    }
    await relogin(user,password,isc).then((b) => {
        alert(b.data.msg)
        captcha=b.data.data.showCaptcha;
    })
    if (captcha) {
      return "https://wap.xybsyw.com/jcaptcha.jpg?v="+Math.random()
    }
    await getcookie().then((res) => {
        const{loginer,schoolName}={...res.data.data}
        msg={loginer,schoolName,...msg}
        
    })
    await getpersoninfo().then(val=>{
        msg={...val.data.data[0],...msg}   
    })
   
    return msg
}

